#!/usr/bin/perl -w

###############################################################################
# Load the processed pheno and pheno_details files into the pheno and
# pheno_details tables in the database respectively.
#
# Parameters needed: dbname, username, temp_dir
# Assumptions: $TEMP_DIR/pheno.out and $TEMP_DIR/pheno_datails.out exist
#
# Author: Herodotos Herodotou and Nedyalko Borisov
# Date: March 11, 2010
#
##############################################################################

use getOpts qw(get_options println);

if ($#ARGV != 0)
{
   println qq(Please specify the .properties file);
   println qq(Usage: perl $0 load.properties);
   exit(-1);
}

# Get input parameters
%opt = get_options($ARGV[0]);
$DB_NAME  =$opt{'dbname'};
$USERNAME =$opt{'username'};
$TEMP_DIR = $opt{'temp_dir'};

println qq(Loading pheno data);

# Drop constraints, load the data, and add constraints
!system qq(psql -U $USERNAME -d $DB_NAME -f sql/drop_pheno_constraints.sql > /dev/null) or die $!;
!system qq(psql -U $USERNAME -d $DB_NAME -c ).
        qq("\\COPY pheno FROM '$TEMP_DIR/pheno.out' WITH DELIMITER AS ','") or die $!;
!system qq(psql -U $USERNAME -d $DB_NAME -f sql/add_pheno_constraints.sql > /dev/null) or die $!;
!system qq(psql -U $USERNAME -d $DB_NAME -c "ANALYZE pheno" > /dev/null) or die $!;

# Load the pheno details data
$load_script = qq($TEMP_DIR/load_pheno.sql);
open  OUTFILE, ">", $load_script or die $!;
print OUTFILE qq(BEGIN TRANSACTION;\n);
print OUTFILE qq(SET CONSTRAINTS ALL DEFERRED;\n);
print OUTFILE qq(\\COPY pheno_details FROM '$TEMP_DIR/pheno_details.out' WITH DELIMITER AS ','\n);
print OUTFILE qq(COMMIT;\n);
close OUTFILE;

!system qq(psql -U $USERNAME -d $DB_NAME -f $load_script > /dev/null) or die $!;
!system qq(psql -U $USERNAME -d $DB_NAME -c "ANALYZE pheno_details" > /dev/null) or die $!;
!system qq(rm -f $load_script) or die $!;

# Remove the out files
!system qq(rm -f $TEMP_DIR/pheno.out) or die $!;
!system qq(rm -f $TEMP_DIR/pheno_details.out) or die $!;

println qq(Completed loading pheno data);

